app.controller("taxInfoController",function ($scope, $controller,$location,taxInfoService, uploadService) {

    $controller("baseController",{$scope:$scope});

    //定义模糊查询对象
    $scope.searchEntity = {};

    $scope.entity = {stepRateList:[{prefix:0,suffix:0,personalTax:0,valueAddedTax:0,laborServiceFee:0}]};

    $scope.taxInvoiceCategoryList = []
    $scope.arrApp = [];
    // 发票类目对象
    // $scope.categoryParam = {"id": null, "invoiceCategories": null};
    // 是否是税地运营账号
    $scope.isTax = false

    //获取税地信息
    $scope.findPage = function (pageNum, pageSize) {

        if (pageNum == null)
            pageNum = 1;

        if (pageSize == null)
            pageSize = 10;

        taxInfoService.findPage(pageNum,pageSize,$scope.searchEntity).success(function (response) {

            if (response.code == 200){

                $scope.taxInfoList = response.data;

                //更新总记录数
                $scope.paginationConf.totalItems=response.total;

            } else {
                alert(response.msg);
            }

        })

    };

    //根据税地id回去明细
    $scope.findOne = function () {

        var taxInfoId = $location.search()['taxInfoId'];

        if (taxInfoId == null){

            return;
        }


        taxInfoService.findOne(taxInfoId).success(function (response) {

            if (response.code == 200){
                // $scope.categoryParam.id = taxInfoId
                $scope.entity = response.data;

                $scope.findSubBalance($scope.entity.shadowSubAccount,$scope.entity.id);
                var stepRateList = $scope.entity.stepRateList;
                
                if (stepRateList == null || stepRateList.length == 0){

                    $scope.entity.stepRateList = [{prefix:0,suffix:0,personalTax:0,valueAddedTax:0,laborServiceFee:0}];

                } else {

                    for (var i = 0; i < stepRateList.length; i++) {
                        console.log(stepRateList[i].prefix/10000)
                        //前缀
                        stepRateList[i].prefix = stepRateList[i].prefix/10000;

                        //后缀
                        stepRateList[i].suffix = stepRateList[i].suffix/10000;

                        //个税
                        stepRateList[i].personalTax = stepRateList[i].personalTax * 100;

                        //增值税
                        stepRateList[i].valueAddedTax = stepRateList[i].valueAddedTax * 100;

                        //服务费
                        stepRateList[i].laborServiceFee = stepRateList[i].laborServiceFee * 100;

                        //总额外加收费率
                        stepRateList[i].extraRate = $scope.numMulti(stepRateList[i].extraRate,100);


                    }

                    // $scope.entity.stepRateList = $scope.entity.stepRateListView;

                }

                // 发票类目
                /*let selectedInvoiceCategories = ''
                let ids = $scope.entity.invoiceCategories ? JSON.parse($scope.entity.invoiceCategories) : [];
                for (let i = 0; i < ids.length; i++) {
                    const id = ids[i]
                    let obj = $scope.taxInvoiceCategoryList.find(ele => {
                        return ele.id === id
                    })
                    if (obj && obj !== null) {
                        $scope.arrApp.push(obj.id)
                        selectedInvoiceCategories += '【'+ obj.categoryName +'】'
                    }
                }

                $scope.entity['selectedInvoiceCategories'] = selectedInvoiceCategories ? selectedInvoiceCategories : '暂无'*/

                if ($scope.entity.businessInfo) {
                    let businessInfo = JSON.parse($scope.entity.businessInfo)
                    $scope.entity['regMoney'] = businessInfo.regMoney
                    $scope.entity['businessScope'] = businessInfo.businessScope
                    $scope.entity['buildTime'] = businessInfo.buildTime
                }
            } else {
                alert(response.msg);
            }

        })

    };


    //新增或更新
    $scope.insertOrUpdate = function () {


        if ($scope.isClick){
            console.log("重复提交");
            return;
        }
        console.log($scope.entity)
        //标记为点击状态
        $scope.isClick = true;

        var isError = false;

        if ($scope.isNull($scope.entity.name)){
            alert("未设置名称");
            isError = true;

        }

        if ($scope.isNull($scope.entity.adress)) {
            alert("未设置地址");
            isError = true;

        }

        if ($scope.isNull($scope.entity.contacts)) {
            alert("未设置联系人");
            isError = true;

        }

        if ($scope.isNull($scope.entity.phone)){
            alert("未设置手机号");
            isError = true;

        }

        // if ($scope.isNull($scope.entity.signedAdress)){
        //     alert("未设置签订地点");
        //     isError = true;
        // }



        if ($scope.isNull($scope.entity.isClose)){
            alert("未设置税地状态");
            isError = true;
        }
        //默认关闭限额，开启阶梯限额
        $scope.entity.isQuota = 0;
        if ($scope.isNull($scope.entity.isQuota)){
            alert("未设置限额状态");
            isError = true;
        }

        //开启限额时 不能为空
        if ($scope.entity.isQuota == 1){
            
            if ($scope.isNull($scope.entity.quota)){
                alert("未设置限额");
                isError = true;

            } 
            
            if ($scope.entity.quota <=0 ){
                alert("限额金额不正确")
                isError = true;
            } 

        }

        // if ($scope.isNull($scope.entity.isStepRate)){
        //     alert("未设置阶梯状态");
        //     isError = true;
        //
        // }

        //税地关闭 提示不能为空
        if ($scope.entity.isClose == 0) {

            if ($scope.isNull($scope.entity.closeTips)){
                alert("未设置关闭提示");

                isError = true;

            }

        }

        //阶梯状态为开启是 阶梯费率不能为空
        // if ($scope.entity.isStepRate == 1) {
        //
        //     var stepRateList = $scope.entity.stepRateList;
        //
        //     if (stepRateList == null || stepRateList.length == 0){
        //         alert("未设置阶梯费率");
        //         isError = true;
        //     }
        //
        //     for (var i = 0; i < stepRateList.length; i++) {
        //
        //         if (stepRateList[i].personalTax == null ||  stepRateList[i].personalTax == 0) {
        //             alert("个税不能为0");
        //
        //             isError = true;
        //             break;
        //         }
        //
        //     }
        //
        // }else {
        //
        //     $scope.entity.stepRateList = [];
        // }

        var stepRateList = $scope.entity.stepRateList;

        if (stepRateList == null || stepRateList.length == 0){
            alert("未设置阶梯费率");
            isError = true;
        }

        for (var i = 0; i < stepRateList.length; i++) {

            if (i == 0){

                if (stepRateList[i].prefix == null ||  stepRateList[i].prefix < 0) {
                    alert("第 "+(i + 1)+" 阶梯前缀错误");

                    isError = true;
                    break;
                }

            }

            if (i != 0){

                if (stepRateList[i].prefix == null ||  stepRateList[i].prefix <= 0) {
                    alert("第 "+(i + 1)+" 阶梯前缀错误");

                    isError = true;
                    break;
                }

            }

            if (stepRateList[i].suffix == null ||  stepRateList[i].suffix <= 0) {
                alert("第 "+(i + 1)+" 阶梯后缀错误");

                isError = true;
                break;
            }

            if (stepRateList[i].personalTax == null ||  stepRateList[i].personalTax <= 0) {
                alert("第 "+(i + 1)+" 阶梯个税错误");

                isError = true;
                break;
            }

        }

        if (isError){//参数错误是还原按钮状态
            //还原按钮初始状态
            $scope.isClick = false;
            return;
        }

        var serviceObj;
        $scope.entity.isStepRate = 1;
        if ($scope.entity.id == null){


            serviceObj = taxInfoService.insert($scope.entity);
        } else {
            $scope.entity.isStepRate = 1;
            serviceObj = taxInfoService.update($scope.entity);
        }

        // 工商信息
        $scope.entity.businessInfo = {}
        let businessInfo = {
            regMoney: $scope.entity.regMoney,
            businessScope: $scope.entity.businessScope,
            buildTime: $scope.entity.buildTime
        }
        $scope.entity.businessInfo = JSON.stringify(businessInfo)
        serviceObj.success(function (response) {

            if (response.code == 200){

                $scope.entity = {};

                location.href = "taxInfo-manage.html"


            } else {
                alert(response.msg);

            }

            //还原按钮初始状态
            $scope.isClick = false;
        }).error(function () {
            //还原按钮初始状态
            $scope.isClick = false;
        });


    };



    //标记阶梯数
    $scope.indexStepRateList = ["StepTate"];


    //添加阶梯级数
    $scope.updateIndexStepTateList = function(){
        console.log("添加执行了");

        $scope.indexStepRateList.push("StepTate");

    };


    //增加阶梯级数
    $scope.createStepList = function(){
        

        var stepTate = {prefix:0,suffix:0,personalTax:0,valueAddedTax:0,laborServiceFee:0};

        var addLength = $scope.indexStepRateList.length - $scope.entity.stepRateList.length;


        for (var j = 0; j < addLength; j++) {//循环选中规格的结果集


            $scope.entity.stepRateList.push(stepTate);


        }
            // alert("赋值后："+JSON.stringify($scope.entity.stepTateList))

    };

    //删除阶梯费率的一行
    $scope.deletestepTateRow = function (index) {

        if ($scope.entity.stepRateList.length == 1)
            return;

        $scope.entity.stepRateList.splice(index,1);

        $scope.indexStepRateList.splice(index,1);
    };

    // $scope.$watch("entity.isStepRate",function (newVale, oldVale) {
    //
    //     if (newVale == null)
    //         return;
    //
    //     alert("新的值：" + newVale)
    // })

    //上传身份证
    $scope.uploadQualification = function (type) {
        console.log(1111)
        if (type == 1) {
            //营业执照
            uploadService.uploadTaxInfoBusinessLicense().success(function (response) {
                if (response.code == 200) {
                    $scope.uploadParam.businessLicenseUrl = response.data;
                    alert('上传成功，点击 "保存" 按钮保存')
                } else {
                    alert(response.msg);
                }

            });
        } else if (type == 2) {
            //委托代征资质
            uploadService.uploadTaxInfoEntrustmentQualification().success(function (response) {
                if (response.code == 200) {
                    $scope.uploadParam.entrustmentQualificationUrl = response.data;
                    alert('上传成功，点击 "保存" 按钮保存')
                } else {
                    alert(response.msg);
                }

            });
        }

    };
    //上传合同时添加企业id
    $scope.addTaxInfoId = function (taxInfoId) {
        $scope.uploadParam.taxInfoId = taxInfoId;
    };

    $scope.uploadParam = {taxInfoId: null, "businessLicenseUrl": null,"entrustmentQualificationUrl": null, type: 0};

    //添加合同Url
    $scope.addQualification = function (type) {
        console.log("type")
        console.log(type)
        if (type ===1 && $scope.uploadParam.businessLicenseUrl == null) {
            alert("未上传营业执照");
            return;
        }
        if (type ===2 && $scope.uploadParam.entrustmentQualificationUrl == null) {
            alert("未上传资质");
            return;
        }
        $scope.uploadParam.type = type
        taxInfoService.addLicenseQualification($scope.uploadParam).success(function (response) {

            if (response.code == 200) {

                $scope.reloadList();

            } else {

                alert(response.msg);
            }

        });

    };

    $scope.getAllInvoiceCategory = function () {
        taxInfoService.findAllInvoiceCategory().success(function (response) {
            $scope.taxInvoiceCategoryList = response.data
            if(sessionStorage.getItem("isTax")) {
                $scope.isTax = true
            }
        })
    }


    $scope.checkFirst = function(id){
        let index = $scope.arrApp.findIndex(ele => {
            return ele === id
        })
        return index > -1
    }

    $scope.checkFirstAll = function(){
        return $scope.arrApp.length === $scope.taxInvoiceCategoryList.length
    }
    //全选
    $scope.categorySelectAll = function() {
        if ($scope.arrApp.length === $scope.taxInvoiceCategoryList.length) {
            $scope.arrApp = []
        } else {
            $scope.arrApp = []
            $scope.taxInvoiceCategoryList.forEach(item => {
                $scope.arrApp.push(item.id)
            })
        }
    }
    // 如果需要选中默认值或者带入默认选项需要循环出所以key值添加到数组中
    $scope.categorySelect = function(id){
        let index = $scope.arrApp.indexOf(id);
        if( index < 0 ){
            $scope.arrApp.push(id);
        }else{
            $scope.arrApp.splice(index,1);
        }
        console.log($scope.arrApp)
    }


    // 更新税地开票类目
    $scope.updateTaxInvoiceCategory = function(){
        $scope.categoryParam.invoiceCategories = JSON.stringify($scope.arrApp)
        taxInfoService.updateByPrimaryKeySelective($scope.categoryParam).success(function (response) {
            if (response.code == 200) {
                $scope.findOne()
                alert('修改成功')
            } else {
                alert(response.msg);
            }
        })
    }

    //查询平安清分子账户余额
    $scope.findSubBalance = function (subAccount,taxInfoId) {

        if ($scope.isNull(subAccount)){
            console.log("清分子账户缺失")
            return;
        }

        taxInfoService.findSubBalance(subAccount,taxInfoId).success(function (res) {
            if (res.code == 200) {
                $scope.shadowSubAccountBalance = res.data;
            } else {
                $scope.shadowSubAccountBalance = res.msg;
            }

        })

    }

    $scope.taxInfoInvoiceExampleParam = {};
    $scope.addExampleTaxInfoId = function (id) {
        $scope.taxInfoInvoiceExampleParam = {};
        $scope.taxInfoInvoiceExampleParam.taxInfoId = id
    }

    // 上传样张
    $scope.uploadTaxInfoInvoiceExamples = function (type) {
        if ($scope.taxInfoInvoiceExampleParam.taxInfoId === null ) {
            alert("参数错误，请返回重试");
            return;
        }
        $scope.taxInfoInvoiceExampleParam.type = type
        uploadService.uploadInvoiceExamples($scope.taxInfoInvoiceExampleParam).success(function (res) {
            if (res.code === 200) {
                const file = document.getElementById(`invoice_example_file${type}`);
                file.outerHTML = file.outerHTML;
                alert("修改成功");
            } else {
                alert(res.msg);
            }

        })

    }

    $scope.saveNewInvoiceCategory = function () {
        let value = document.getElementById("newInvoiceCategory").value;
        let elementById = document.getElementById("dangerAlert");
        if (value) {
            taxInfoService.insertInvoiceCategory({categoryName: value}).success(function (response) {
                if (response.code === 200) {
                    $scope.getAllInvoiceCategory()
                } else {
                    alert(response.msg)
                }
            })
            elementById.style.display = 'none'
        } else {
            elementById.style.display = 'block'
        }
    }
});